<?php
namespace Admin\Controller;
require_once 'Qiniu/autoload.php';
use \Qiniu\Auth;
use \Qiniu\Storage\UploadManager;
use Think\Controller;

class SpecialController extends Controller {
	/**
	 * 专题管理
	 * @return [type] [description]
	 */
	public function index() {
        $putPolicy=array(
            'saveKey'=>'themeList/$(etag)',
        );
        $upAuth = new Auth(C('QINIU_accessKey'), C('QINIU_secretKey'));
        //$bucket = 'images';
        $bucket = C('QINIU_BUCKET');
        $uploadToken = $upAuth->uploadToken($bucket,null, 3600,$putPolicy);


        $this->assign('uploadToken', $uploadToken);

		$map = array();

		$name = I('get.name');
		if($name) {
			$map['name'] = $name;
		}

        $model = M('FrontTheme');
        $total = $model->order('sort DESC')->where($map)->count();
        $page = new \Think\Page($total, 25);
        $show = $page->show();

        $specialList = $model->where($map)
        			 ->order('sort DESC')
                     ->limit($page->firstRow .',' . $page->listRows)
                     ->select();

		$this->assign('showpage', $show);
		$this->assign('specialList', $specialList);

		$this->display();
	}	

	/**
	 * 添加专题
	 */
	public function addSpecial() {
		if(IS_POST) {
			$dataGet['name'] = I('post.name', '');
			$dataGet['status'] = I('post.status', 1); // 文稿标题
			$dataGet['create_time'] = time();
			$dataGet['update_time'] = time();
            $dataGet['image_url']=I('post.image_url');
			/*if($_FILES['image_url']['size'] > 0) {
				$upload = new \Think\Upload();
			    $upload->maxSize   =     3145728 ;// 设置附件上传大小
			    $upload->exts      =     array('jpg', 'gif', 'png', 'jpeg');
			    $upload->rootPath  =     './Html/Uploads/special/';
			    $upload->savePath  =     '';
			    $info   =   $upload->upload();
			    if(!$info) {// 上传错误提示错误信息
			        $this->error($upload->getError());
			    }else{
			    	$dataGet['image_url'] = 'special/'. $info['image_url']['savepath'] . $info['image_url']['savename'];
			    }

			}*/

			$rules = array(
			    array('name','require','专题名称必须填写'),
			);

			$model = M('FrontTheme');
			if (!$model->validate($rules)->create($dataGet)){
			    $this->error($model->getError());
			}else{
			    $res = $model->add($dataGet);
			    if($res) {
			    	$model->save(array('id'=>$res,'sort'=>$res));
			    	$this->success('添加成功');
			    } else {
			    	$this->error('添加失败');
			    }
			}

		}
	}

	/**
	 * 修改专题
	 * @return [type] [description]
	 */
	public function editSpecial() {
		if(IS_POST) {
			$dataGet['id'] = I('post.id', '');
			$dataGet['name'] = I('post.name', '');
			$dataGet['status'] = I('post.status', 1); // 文稿标题
			$dataGet['update_time'] = time();
            $dataGet['image_url']=I('post.image_url');

			/*if($_FILES['image_url']['size'] > 0) {
				$upload = new \Think\Upload();
			    $upload->maxSize   =     3145728 ;// 设置附件上传大小
			    $upload->exts      =     array('jpg', 'gif', 'png', 'jpeg');
			    $upload->rootPath  =     './Html/Uploads/special/'; 
			    $upload->savePath  =     ''; 
			    $info   =   $upload->upload();
			    if(!$info) {// 上传错误提示错误信息
			        $this->error($upload->getError());
			    }else{
			    	$dataGet['image_url'] = 'special/'. $info['image_url']['savepath'] . $info['image_url']['savename'];
			    }

			}*/

			$rules = array(
			    array('name','require','专题名称必须填写'), 
			);

			$model = M('FrontTheme');
			if (!$model->validate($rules)->create($dataGet)){
			    $this->error($model->getError());
			}else{
			    $res = $model->save($dataGet);
			    if($res !== false) {
			    	$this->success('修改成功');
			    } else {
			    	$this->error('修改失败');
			    }
			}

		}
	}


	/**
	 * ajax获取专题信息
	 * @param  integer $id [description]
	 * @return [type]      [description]
	 */
    public function ajaxGetSpecialInfo($id=0){
        $model = M('FrontTheme');
        if($id){
            $info = $model->where('id=' . $id)->find();
            if($info){
                $this->ajaxReturn($info);
            }else{
                $this->ajaxReturn(0);
            }
        }else{  
            return false;
        }
    }

	/**
	 * 删除专题
	 * @return [type] [description]
	 */
	public function ajaxDelSpecial() {
		if(IS_GET) {
			$id = I('get.id');
		} elseif(IS_POST) {
			$id = I('post.id');
			is_array($id) && $id = implode(',', $id);
		}

		if(empty($id)) {
			$message['status'] = -1;
			$message['msg'] = '选项不能为空';
			$this->ajaxReturn($message);
		}

		$map['id'] = array('in', $id);
		$res = M('FrontTheme')->where($map)->delete();
		if($res) {
			$message['status'] = 1;
			$message['msg'] = '删除成功';
			$this->ajaxReturn($message);			
		} else {
			$message['status'] = -1;
			$message['msg'] = '删除失败，请重试';
			$this->ajaxReturn($message);
		}
	}

	public function getSpecialList() {
		$sid = I('get.sid');
		$model = M('FrontTheme');
		$map = array();
		$name = I('get.name');
		if($name) {
			$map['name'] = $name;
		}

        $list = $model->where($map)->select();
        $total = count($list);
        $page = new \Think\Page($total, 10);
        $show = $page->show();

        $specialList = $model->where($map)
        			 ->order('sort DESC')
                     ->limit($page->firstRow .',' . $page->listRows)
                     ->select();

        foreach($specialList as $key => $val) {
        	$tmp = M('FrontThemeRecord')->where(array('theme_id' => $sid, 's_theme_id' => $val['id']))->find();
        	if($tmp) {
        		$specialList[$key]['is_add'] = 1;
        	} else {
        		$specialList[$key]['is_add'] = 0;
        	}
        }


		$this->assign('showpage', $show);
		$this->assign('specialList', $specialList);

		$this->display();
	}

	public function getLiveList() {
		$sid = I('get.sid');
		$model = M('Live');
		$map = array('v_status'=>1);

		$name = I('get.name');
		if($name) {
			$map['title'] = array('like',"%$name%");
		}

        $list = $model->where($map)->group('group_id')->select();
        $total = count($list);
        $page = new \Think\Page($total, 24);
        $show = $page->show();

        $liveList = $model->where($map)
        			 ->order('start_time DESC')
        			 ->group('group_id')
                     ->limit($page->firstRow .',' . $page->listRows)
                     ->select();

        foreach($liveList as $key => $val) {
        	$tmp = M('FrontThemeRecord')->where(array('theme_id' => $sid, 'live_group_id' => $val['group_id']))->find();
        	if($tmp) {
        		$liveList[$key]['is_add'] = 1;
        	} else {
        		$liveList[$key]['is_add'] = 0;
        	}
        }


		$this->assign('showpage', $show);
		$this->assign('liveList', $liveList);

		$this->display();
	}


	/**
	 * 管理内容
	 * @return [type] [description]
	 */
	public function manageSpecialContent() {
        $sid=I('get.sid');
        $count=M('FrontThemeRecord')->where(array('theme_id'=>$sid))->count();
        $page = new \Think\Page($count, 20);

        $contentList=M('FrontThemeRecord')->order('sort Desc')->where(array('theme_id'=>$sid))->limit($page->firstRow .',' . $page->listRows)->select();
        foreach($contentList as $k=>$v){
            if($v['live_group_id']){
                $r=M('Live')->where(array('group_id'=>$v['live_group_id']))->find();
                $contentList[$k]['title']=$r['title'];
                $contentList[$k]['image_url']=$r['image_url'];
                $contentList[$k]['type']='live';
            }else if($v['s_theme_id']){
                $r=M('FrontTheme')->find($v['s_theme_id']);
                $contentList[$k]['title']=$r['name'];
                $contentList[$k]['image_url']=$r['image_url'];
                $contentList[$k]['type']='special';
            }
        }
        $show = $page->show();

        $this->assign('showpage', $show);
        $this->assign('contentList', $contentList);
        $this->display();
	}

	public function addSpecialLiveAll(){
		$group_idall = I('post.group_id_all');
		$group_idall =explode(',',$group_idall);
		$temp1=array();
		$temp2=array();
		foreach($group_idall as $v){
			$a=$this->addSpecialLiveAction($v);
			if($a['status']!=1){
				$temp1[]=$v;
			}else{
				$temp2[]=$v;
			}
		}
		$this->ajaxReturn(array(
			'error'=>$temp1,
			'success'=>$temp2
		));

	}

	public function addSpecialLive($group_id) {
		$a=$this->addSpecialLiveAction($group_id);
		if($a['status']==1){
			$this->success($a['info']);
		}else{
			$this->error($a['info']);
		}
	}

	public function addSpecialLiveAction($group_id) {
		$sid = I('get.sid');
		if($sid) {
			if($group_id) {
				$live_info = M('Live')
							->where(array('group_id' => $group_id))
							->group('group_id')->find();

				$dataGet['theme_id'] = $sid;
				$dataGet['live_group_id'] = $group_id;
				$dataGet['update_time'] = time();
				// $dataGet['sort'] = $live_info['start_time'];
				$res = M('FrontThemeRecord')->add($dataGet);
				if($res) {
					M('FrontThemeRecord')->save(array('id'=>$res,'sort'=>$res));
					return array('status'=>1,'info'=>'添加成功');
				} else {
					return array('status'=>0,'info'=>'添加失败');
				}

			} else {
				 return array('status'=>0,'info'=>'直播ID不存在');
			}

		} else {
			 return array('status'=>0,'info'=>'栏目ID不存在');
		}
	}

	public function addSpecialToSpec() {
		$sid = I('get.sid');
		$ssid = I('get.ssid');
		if($sid) {
			if($ssid) {
				$dataGet['theme_id'] = $sid;
				$dataGet['s_theme_id'] = $ssid;
				$dataGet['type'] = 'special';
				$dataGet['update_time'] = time();

				$res = M('FrontThemeRecord')->add($dataGet);
				if($res) {
					$this->success('添加成功');
				} else {
					$this->error('添加失败');
				}

			} else {
				$this->error('直播ID不存在');
			}

		} else {
			$this->error('栏目ID不存在');
		}
	}

	public function getLiveListWithPub() {
		$sid = I('get.sid');
		$pModel = M('FrontThemeRecord');
		$map['p.theme_id'] = $sid;

		$name = I('get.name');
		if($name) {
			$map['l.name'] = $name;
		}

        $list = $pModel->alias('p')->where($map)->select();
        $total = count($list);
        $page = new \Think\Page($total, 10);
        $show = $page->show();

        $pList = $pModel->alias('p')
        			 ->field('p.id pubid,p.sort psort,l.*')
        			 ->join('__LIVE__ AS l ON p.live_group_id = l.group_id')
        			 ->where($map)
        			 ->order('p.sort DESC')
        			 ->group('l.group_id')
                     ->limit($page->firstRow .',' . $page->listRows)
                     ->select();

		$this->assign('showpage', $show);
		$this->assign('pList', $pList);

		$this->display();	
	}

	public function getSpecialListWithPub() {
		$sid = I('get.sid');
		$pModel = M('FrontThemeRecord');
		$map['p.theme_id'] = $sid;

		$name = I('get.name');
		if($name) {
			$map['ft.name'] = $name;
		}

        $list = $pModel->alias('p')->where($map)->select();
        $total = count($list);
        $page = new \Think\Page($total, 10);
        $show = $page->show();

        $pList = $pModel->alias('p')
        			 ->field('p.id pubid,p.sort psort,ft.*')
        			 ->join('__FRONT_THEME__ AS ft ON p.s_theme_id = ft.id')
        			 ->where($map)
        			 ->order('p.sort DESC')
                     ->limit($page->firstRow .',' . $page->listRows)
                     ->select();

		$this->assign('showpage', $show);
		$this->assign('pList', $pList);

		$this->display();	
	}

	public function delSpecialContent() {
		$id = I('get.id');

		if(empty($id)) {
			$this->error('ID不能为空');
		}

		$map['id'] = array('in',$id);
		$res = M('FrontThemeRecord')->where($map)->delete();
		if($res) {
			$this->success('删除成功');			
		} else {
			$this->error('删除失败，请重试');
		}		
	}


	public function ajaxGetSort($id = 0) {
        $model = M('FrontThemeRecord');
        if($id){
            $info = $model->where('id=' . $id)->find();
            if($info){
                $this->ajaxReturn($info);
            }else{
                $this->ajaxReturn(0);
            }
        }else{  
            return false;
        }	
	}


	public function setResourceSort() {
		$id = I('post.id');
		$sort = I('post.sort');
        $model = M('FrontThemeRecord');
        if($id){
        	$dataGet['sort'] = $sort;
            $info = $model->where('id=' . $id)->save($dataGet);
            if($info){
                $this->success('更新成功');
            }else{
                $this->error('更新失败');
            }
        }else{
           $this->error('未指定ID');
        }
	}

    public function ajaxSetSort(){
        $ids=I('get.sortedIDs');
        $sortNum=I('get.sortNum');
        M()->startTrans();
        foreach($ids as $k=>$v){
            $res=M('FrontThemeRecord')->save(array('id'=>$v,'sort'=>$sortNum[$k]));
            if($res===false){
                M()->rollback();
                $this->ajaxReturn(array('resultCode'=>1,'info'=>'排序修改失败！'));
            }
        }
        M()->commit();
        $this->ajaxReturn(array('resultCode'=>0,'info'=>'排序修改成功！'));
    }
} 